/*
 * @Description:
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-10-20 22:34:11
 */
package controllers

import (
	. "blogApi/models"
	"strings"

	"github.com/astaxie/beego/orm"
)

// ArticleController ArticleController
type ArticleController struct {
	BaseController
}

// Get Get
func (a *ArticleController) Get() {
	keytitle := strings.TrimSpace(a.GetString("keytitle"))
	page, err := a.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := a.GetInt("limit")
	if err != nil {
		limit = 15
	}
	offset := (page - 1) * limit
	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "status", 1)
	if keytitle != "" {
		filters = append(filters, "title", 1)
	}
	res := make([]*Article, 0)
	o := orm.NewOrm()
	article := new(Article)
	qs := o.QueryTable(article) // 返回 QuerySeter
	if len(filters) > 0 {
		l := len(filters)
		for k := 0; k < l; k += 2 {
			qs = qs.Filter(filters[k].(string), filters[k+1])
		}
	}
	total, _ := qs.Count()
	qs.OrderBy("-created_at").OrderBy("-click").Limit(limit, offset).All(&res)
	list := make([]map[string]interface{}, len(res))
	// 其他参数
	args := make(map[string]interface{})
	args["count"] = total
	for k, v := range res {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["category_id"] = v.CategoryId
		row["title"] = v.Title
		row["author"] = v.Author
		row["content"] = v.Content
		row["markdown"] = v.Markdown
		row["description"] = v.Description
		row["keywords"] = v.Keywords
		row["cover"] = v.Cover
		row["click"] = v.Click
		row["create_at"] = v.CreatedAt
		row["update_at"] = v.UpdatedAt
		list[k] = row
	}
	a.ResJson(0, "获取成功", list, args)
}
